package com.nf.health.app.intervention_details.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.customview.CircleImageView;
import com.nf.health.app.customview.MyGridView;
import com.nf.health.app.download.DownloadProgressListener;
import com.nf.health.app.download.FileDownloader;
import com.nf.health.app.fragment.IBaseFragment;
import com.nf.health.app.inquiry.adapter.SelectServiceDataTypeAdapter;
import com.nf.health.app.inquiry.bean.MySeltctPayTime;
import com.nf.health.app.intervention_details.adapter.MusicAdapter;
import com.nf.health.app.intervention_details.bean.MusicBean;
import com.nf.health.app.intervention_details.bean.MusicVo;
import com.nf.health.app.utils.DateUtil;
import com.nf.health.app.utils.ImageLoaderUtils;
import com.nf.health.app.utils.ModelUtils;
import com.nf.health.app.utils.Player;
import com.nf.health.app.utils.ViewUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 音乐方案详情fragment
 * Created by Administrator on 2016/11/10.
 */
public class MusicdetailsFragment extends IBaseFragment {
    private static final int PROCESSING = 1;
    private static final int FAILURE = -1;

    int status = 1;
    @Bind(R.id.tv_scheme_common_head_title)
    TextView tvSchemeCommonHeadTitle;
    @Bind(R.id.tv_scheme_common_head_content)
    TextView tvSchemeCommonHeadContent;
    @Bind(R.id.yizhouanpai)
    TextView yizhouanpai;
    @Bind(R.id.exercised_image)
    CircleImageView exercisedImage;
    @Bind(R.id.exercised_blod_title)
    TextView exercisedBlodTitle;
    @Bind(R.id.music_content)
    TextView musicContent;
    @Bind(R.id.musiname)
    TextView musiname;
    @Bind(R.id.music_gridview)
    MyGridView musicGridview;
    @Bind(R.id.musicurl)
    TextView musicurl;

    MusicAdapter musicAdapter;
    private int selectdataTypePosition = 0;//默认选中第一条

    private TextView resultView;
    private TextView zong;
    private TextView yiyong;
    private ProgressBar progressBar;
    private ImageButton playBtn;
    public static Player player;
    private SeekBar musicProgress;

    private Handler handler = new UIHandler();
    MusicVo musicVo = new MusicVo();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }



    private final class UIHandler extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PROCESSING: //
                    progressBar.setProgress(msg.getData().getInt("size"));
                    float num = (float) progressBar.getProgress()
                            / (float) progressBar.getMax();
                    int result = (int) (num * 100); //
                    resultView.setText(result + "%");
                    if (progressBar.getProgress() == progressBar.getMax()) {
                    }
                    break;
                case FAILURE: //
                    break;
            }
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        addViewFillInRoot(R.layout.fragment_musicdetails);
        ButterKnife.bind(this, rootView);

        resultView = (TextView) rootView.findViewById(R.id.resultView);
        zong = (TextView) rootView.findViewById(R.id.zong);
        yiyong = (TextView) rootView.findViewById(R.id.yiyong);
        progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
        ButtonClickListener listener = new ButtonClickListener();
        playBtn = (ImageButton) rootView.findViewById(R.id.btn_online_play);
        playBtn.setOnClickListener(listener);
        musicProgress = (SeekBar) rootView.findViewById(R.id.music_progress);
        player = new Player(musicProgress);
        musicProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
        String id = Constants.CHANGE_ABLE.INTERVENTION_ID;
        provider.requesmusic(id, "music");

    }

    private final class ButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_online_play:
                    if (player.mediaPlayer.isPlaying()) {
                        playBtn.setBackgroundResource(R.drawable.iv_paly);
                    } else {
                        playBtn.setBackgroundResource(R.drawable.iv_stop_paly);
                    }

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (player.mediaPlayer.isPlaying()) {
                                player.pause();
                                status = 3;
                            } else {
                                if (status == 1) {
                                    if(musicVo  != null){
                                        if (musicVo.getList()!= null && musicVo.getList().size() > 0) {
                                            if(!TextUtils.isEmpty(musicurl.getText().toString())){
                                                player.playUrl(musicurl.getText().toString());
                                            }else{
                                                player.playUrl(musicVo.getList().get(0).getUrl());
                                            }
                                        }

                                    }
                                } else {
                                    player.start();//继续播放
                                }
                            }

                        }
                    }).start();
//                    }
                    break;
            }
        }

        private DownloadTask task;

        private void exit() {
            if (task != null)
                task.exit();
        }

        private void download(String path, File savDir) {
            task = new DownloadTask(path, savDir);
            new Thread(task).start();
        }

        private final class DownloadTask implements Runnable {
            private String path;
            private File saveDir;
            private FileDownloader loader;

            public DownloadTask(String path, File saveDir) {
                this.path = path;
                this.saveDir = saveDir;
            }

            public void exit() {
                if (loader != null)
                    loader.exit();
            }

            DownloadProgressListener downloadProgressListener = new DownloadProgressListener() {
                @Override
                public void onDownloadSize(int size) {
                    Message msg = new Message();
                    msg.what = PROCESSING;
                    msg.getData().putInt("size", size);
                    handler.sendMessage(msg);
                }
            };

            public void run() {
                try {
                    loader = new FileDownloader(getActivity(), path,
                            saveDir, 3);
                    progressBar.setMax(loader.getFileSize());
                    loader.download(downloadProgressListener);
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendMessage(handler.obtainMessage(FAILURE));
                }
            }
        }
    }

    class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
        int progress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            if(seekBar !=null && player.mediaPlayer != null){
                if(seekBar.getMax() != 0 && player.mediaPlayer.getDuration() !=0){
                    this.progress = progress * player.mediaPlayer.getDuration()
                            / seekBar.getMax();
                    Long size = new Long((long) player.mediaPlayer.getDuration());
                    Long size2 = new Long((long) player.mediaPlayer.getCurrentPosition());
                    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                    formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00:00"));
                    if(size>86400000){//大于1小时、、、
                        zong.setText("00:00:00");
                        yiyong.setText("00:00:00");
                    }else{
                        String hms = formatter.format(size);
                        String hms2 = formatter.format(size2);
                        zong.setText(hms);
                        yiyong.setText(hms2);
                    }
                }
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            player.mediaPlayer.seekTo(progress);
            Long size2 = new Long((long) player.mediaPlayer.getCurrentPosition());
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
            String hms2 = formatter.format(size2);

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player.mediaPlayer.isPlaying() && player != null) {
            player.stop();
            player = null;
        }
    }



    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if ("music".equals(actionName)) {
            musicVo = (MusicVo) object;
            tvSchemeCommonHeadTitle.setText("音乐方案");
            tvSchemeCommonHeadContent.setText(musicVo.getGuide());
            if (musicVo.getList().size() > 0) {
                //赋值默认值
                exercisedBlodTitle.setText("-"+musicVo.getList().get(0).getName()+"-");
                musicContent.setText(musicVo.getList().get(0).getNote());
                ImageLoaderUtils.getinstance(getActivity()).getImage(exercisedImage, musicVo.getList().get(0).getPicture(), R.drawable.default_image);
                musiname.setText(musicVo.getList().get(0).getName());


                musicAdapter = new MusicAdapter(getActivity(), musicVo.getList());
                musicGridview.setAdapter(musicAdapter);
                musicVo.getList().get(0).setIsClick(true);
                musicGridview.setSelection(0);

                musicGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {//选择歌曲页面
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (!player.mediaPlayer.isPlaying()) {
                            MusicBean mySelectpayTime = musicVo.getList().get(position);
                            selectdataTypePosition = position;
                            mySelectpayTime.setIsClick(true);
                            ModelUtils.dealNotSelectStatus2(musicVo.getList(), position, musicAdapter);


                            exercisedBlodTitle.setText("-" + musicVo.getList().get(position).getName() + "-");
                            musicContent.setText(musicVo.getList().get(position).getNote());
                            ImageLoaderUtils.getinstance(getActivity()).getImage(exercisedImage, musicVo.getList().get(position).getPicture(), R.drawable.default_image);
                            musiname.setText(musicVo.getList().get(position).getName());
                            musicurl.setText(musicVo.getList().get(position).getUrl());
                            status = 1;
                            if (player != null) {
                                player.stop();
                                yiyong.setText("00:00:00");
                                zong.setText("00:00:00");
                                musicProgress = (SeekBar) rootView.findViewById(R.id.music_progress);
                                player = new Player(musicProgress);
                                playBtn.setBackgroundResource(R.drawable.iv_paly);
                            }
                        }
                    }
                });
            }

            yizhouanpai.setText("一周监测安排表" + "(" + DateUtil.dateToString(new Date(Long.parseLong(musicVo.getStarttime())), "yyyy-MM-dd") + "至" + DateUtil.dateToString(new Date(Long.parseLong(musicVo.getEndtime())), "yyyy-MM-dd") + ")");
        }
    }
}
